<template>
  <div class="font-inter bg-gray-50 text-gray-800 min-h-screen flex flex-col">
    <!-- 头部导航栏 -->
    <!-- 面包屑导航 -->
    <div class="bg-white border-b border-gray-200">
      <div class="container mx-auto px-4 py-3 text-sm text-gray-500">
        <router-link to="/" class="hover:text-primary">首页</router-link>
        <span class="mx-2"> / </span>
        <router-link to="/cart" class="hover:text-primary">购物车</router-link>
        <span class="mx-2"> / </span>
        <router-link to="/order" class="hover:text-primary">结算</router-link>
        <span class="mx-2"> / </span>
        <span class="text-gray-700">支付</span>
      </div>
    </div>

    <main class="flex-1 py-8 md:py-12">
      <div class="container mx-auto px-4 flex justify-center">
        <div class="max-w-5xl mx-auto px-2 sm:px-4 lg:px-6">
          <h1 class="text-5xl md:text-6xl font-bold text-gray-800 mb-8 text-center">支付订单</h1>
          <div class="bg-white rounded-xl shadow-sm p-8 md:p-10 lg:p-12 w-full">
           <div class="border-b border-gray-200 pb-8">
  <h3 class="text-lg font-medium mb-4">订单商品</h3>
  <div class="space-y-4">
    <!-- 循环展示商品列表 -->
    <div v-for="(item, index) in orderItems" :key="index" class="flex items-center gap-4">
      <img
        :src="item.productImage.startsWith('http') ? item.productImage : `http://127.0.0.1:8000/static/${item.productImage}`"
        :alt="item.productName"
        class="w-16 h-16 object-cover rounded"
      >
      <div class="flex-1">
        <p class="font-medium">{{ item.productName }}</p>
        <p class="text-sm text-gray-500">规格：{{ item.productSpec }}</p>
        <p class="text-sm text-gray-500">数量：{{ item.quantity }}</p>
      </div>
      <p class="font-medium">¥{{ item.unitPrice.toFixed(2) }}</p>
    </div>
  </div>
</div>

        <!-- 原有金额明细区域保持不变（已使用动态数据） -->
<div class="space-y-6 border-b border-gray-200 pb-8">
  <div class="flex justify-between items-center">
    <span class="text-gray-700 text-lg">商品总价</span>
    <span class="text-gray-800 text-lg">￥{{ orderTotal }}</span>
  </div>
  <div class="flex justify-between items-center">
    <span class="text-gray-700 text-lg">运费</span>
    <span class="text-gray-800 text-lg">￥{{ shippingFee }}</span>
  </div>
  <div class="flex justify-between items-center">
    <span class="text-gray-700 text-lg">优惠折扣</span>
    <span class="text-gray-800 text-lg">-￥{{ discount }}</span>
  </div>
  <div class="flex justify-between items-center">
    <span class="text-gray-700 text-lg">应付金额</span>
    <span class="text-gray-800 text-lg font-bold">￥{{ payableAmount }}</span>
  </div>
</div>

            <!-- 支付方式选择 -->
            <div class="space-y-6 pt-8">
              <h3 class="text-gray-700 font-medium mb-4 text-center text-lg">选择支付方式</h3>
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                <!-- 微信支付 -->
                <div
                    class="payment-option border rounded-lg p-6 flex items-center justify-between transition-all duration-300 cursor-pointer"
                    :class="{ 'active-payment': selectedPayment === 'wechat' }"
                    @click="selectedPayment = 'wechat'"
                    data-payment="wechat"
                >
                  <img src="https://picsum.photos/id/237/40/40" alt="微信支付" class="w-12 h-12">
                  <span class="text-gray-800 text-lg">微信支付</span>
                </div>

                <!-- 支付宝支付 -->
                <div
                    class="payment-option border rounded-lg p-6 flex items-center justify-between transition-all duration-300 cursor-pointer"
                    :class="{ 'active-payment': selectedPayment === 'alipay' }"
                    @click="selectedPayment = 'alipay'"
                    data-payment="alipay"
                >
                  <img src="https://picsum.photos/id/238/48/48" alt="支付宝支付" class="w-12 h-12">
                  <span class="text-gray-800 text-lg">支付宝支付</span>
                </div>

              </div>
            </div>

            <!-- 支付按钮 -->
            <div class="flex flex-col sm:flex-row gap-6 pt-8">
                <button
                id="pay-button"
                class="flex-1 bg-primary hover:bg-dark text-white font-medium py-4 px-8 rounded-lg transition-colors flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed text-lg"
                :disabled="!selectedPayment || isLoading"
                @click="handlePayment"
              >
                <span v-if="isLoading" class="fa fa-spinner fa-spin mr-2 text-lg"></span>
                <span v-else class="fa fa-credit-card mr-2 text-lg"></span>
                {{ isLoading ? '支付处理中...' : '确认支付' }}
              </button>

            </div>
          </div>
        </div>
      </div>
    </main>

    <Footer />
    <!-- 返回顶部按钮 -->
    <transition name="fade">
      <button
        id="back-to-top"
        class="fixed bottom-6 right-6 bg-primary hover:bg-dark text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg transition-all z-50"
        v-show="showBackTop"
        @click="toTop"
      >
        <span class="fa fa-arrow-up"></span>
      </button>
    </transition>

    <!-- 支付成功弹窗，通过v-if控制显示 -->
    <div v-if="showPaySuccess" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg p-8 max-w-md w-full mx-4 text-center transform transition-all duration-300 scale-100">
        <div class="text-green-500 text-5xl mb-4">
          <i class="fa fa-check-circle"></i>
        </div>
        <h3 class="text-2xl font-bold text-gray-800 mb-2">支付成功</h3>
        <p class="text-gray-600 mb-6">您的订单已完成支付，感谢您的购买</p>
        <button
          class="bg-primary hover:bg-dark text-white px-6 py-3 rounded-lg transition-colors font-medium w-full"
          @click="onSuccessConfirm"
        >
          确定
        </button>
      </div>
    </div>
  </div>
</template>

<script>
// 引入Font Awesome图标样式
import 'font-awesome/css/font-awesome.min.css'
import api from "@/api/request";
import Footer from "@/components/Footer.vue"; // 假设Footer组件路径

export default {
  name: 'Pay',
  components: {
    Footer // 注册Footer组件
  },
  data() {
    return {
      // 移动端菜单状态
      isMobileMenuOpen: false,
      isLoading: false,  // 添加加载状态变量
      // 选中的支付方式
      selectedPayment: '',
      // 订单金额相关数据
      orderId: '',
      orderTotal: '0.00',
      shippingFee: '0.00',
      discount: '0.00',
      orderItems: [],
      // 显示返回顶部按钮
      showBackTop: false,
      // 支付成功弹窗显示状态
      showPaySuccess: false,
      // 订单编号
      orderNumber: '',
      // 支付方式
      paymentMethod: '',
      // 订单状态
      orderStatus: ''
    }
  },
  computed: {
    // 计算应付金额
    payableAmount() {
      const total = parseFloat(this.orderTotal) + parseFloat(this.shippingFee) - parseFloat(this.discount)
      return total.toFixed(2)
    }
  },
mounted() {
  // 从URL参数获取订单信息
  const { orderNumber, totalAmount, paymentMethod } = this.$route.query;
  console.log('路由参数:', this.$route.query); // 调试用

  if (orderNumber) {
    this.orderNumber = orderNumber;
    this.orderTotal = totalAmount || '0.00';
    // 预选择支付方式
    if (paymentMethod === '在线支付') {
      this.selectedPayment = 'wechat';
    }
    // 加载完整订单详情
    this.loadOrderDetails(orderNumber);
  } else {
    console.error('未获取到订单号');
    this.$router.push('/order'); // 跳回订单页
  }

  // 绑定滚动事件
  window.addEventListener('scroll', this.handleScroll)
},
  beforeDestroy() {
    // 移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    // 切换移动端菜单
    toggleMobileMenu() {
      this.isMobileMenuOpen = !this.isMobileMenuOpen
    },

    // 加载订单详情接口
    async loadOrderDetails(orderNumber) {
      try {
        this.orderId = orderNumber;
        console.log('加载订单详情:', this.orderId);

        // 检查是否配置了axios
        if (!this.$axios) {
          throw new Error('axios未正确配置');
        }

        const response = await this.$axios.get(`http://127.0.0.1:8000/order/${this.orderId}`)
        console.log('订单详情:', response.data)
        const order = response.data

        this.orderId = order.id;
        this.orderTotal = order.total_amount.toFixed(2);
        this.shippingFee = order.delivery_fee ? order.delivery_fee.toFixed(2) : '0.00';
        this.discount = order.discount || '0.00'; // 确保折扣有默认值
        this.paymentMethod = order.payment_method;
        this.orderStatus = order.status;
        // 补充订单商品数据
        if (order.items) {
          this.orderItems = order.items;
        }
      } catch (error) {
        console.error('获取订单详情失败:', error);
        alert(`获取订单详情失败：${error.message}`)
      }
    },

    // 处理支付逻辑
    async handlePayment() {
      if (!this.selectedPayment) {
        alert('请选择支付方式');
        return;
      }
       try {
        // 显示加载状态
        this.isLoading = true;

        // 1. 调用后端支付确认接口
        const response = await this.$axios.put(
          `http://127.0.0.1:8000/order/${this.orderId}/pay`
        );

        // 2. 检查接口返回状态
        if (response.code === 200) {
          // 3. 显示支付成功弹窗
          alert("支付成功，现在可去查看个人中心中我的订单")
          this.$router.push('/user-center')
          this.showPaySuccess = true;

          // 4. 可以在这里更新本地订单状态
          this.orderStatus = "processing";
          this.paymentStatus = "paid";
        } else {
          alert(`支付失败: ${response.data.message}`);
        }
      } catch (error) {
        console.error('支付接口调用失败:', error);
        // 错误处理
        if (error.response) {
          alert(`支付失败: ${error.response.data.detail || error.response.data.message}`);
        } else {
          alert('支付过程中发生错误，请稍后重试');
        }
      } finally {
        // 隐藏加载状态
        this.isLoading = false;
      }


    },

    // 支付成功后确认
    onSuccessConfirm() {
      this.showPaySuccess = false;

      // 跳转到订单详情页或首页
      this.$router.push(`/order/detail/${this.orderNumber}`);
    },

    // 滚动事件处理
    handleScroll() {
      this.showBackTop = window.scrollY > 300
    },

    // 返回顶部
    toTop() {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  }
}
</script>

<style scoped>
/* 表单框样式 */
.form-container {
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  max-width: 600px;
  margin: 0 auto;
}

/* 标题样式 */
h1.text-5xl {
  color: #1f2937;
  margin-bottom: 2rem;
  text-align: center;
  font-size: 2rem;
}

/* 订单商品区域样式 */
.border-b {
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 1.5rem;
  margin-bottom: 1.5rem;
}

h3.text-lg {
  color: #1f2937;
  font-weight: 600;
  margin-bottom: 1rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px dashed #e5e7eb;
}

/* 商品列表样式 */
.space-y-4 > div {
  padding: 0.75rem 0;
  border-bottom: 1px solid #f3f4f6;
}

.space-y-4 > div:last-child {
  border-bottom: none;
}

/* 金额明细区域样式 */
.space-y-6.border-b {
  padding: 1rem 0;
}

.space-y-6.border-b > div {
  padding: 0.5rem 0;
  display: flex;
  justify-content: space-between;
}

/* 支付方式选择区域样式 */
.pt-8 {
  padding-top: 1.5rem !important;
}

.grid-cols-1.sm\:grid-cols-2 {
  gap: 1rem;
  margin-top: 1rem;
}

.payment-option {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 1rem;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.payment-option:hover {
  border-color: #8B5A2B;
  background-color: #FCFAF7;
}

.payment-option.active-payment {
  border-color: #8B5A2B;
  background-color: #FCFAF7;
}

.payment-option.active-payment::after {
  content: "✓";
  position: absolute;
  top: 8px;
  right: 8px;
  color: #8B5A2B;
  font-weight: bold;
  background-color: #FCFAF7;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 支付按钮样式 */
.flex.flex-col.sm\:flex-row {
  margin-top: 1.5rem;
}

#pay-button {
  width: 100%;
  background-color: #8B5A2B;
  color: white;
  font-weight: 600;
  padding: 1rem;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

#pay-button:hover {
  background-color: #704620;
}

/* 调整整体间距 */
main.py-8 {
  padding: 2rem 0;
}

.bg-white.rounded-xl {
  border-radius: 8px;
  padding: 2rem;
}

/* 金额加粗样式 */
span.text-gray-800.text-lg.font-bold {
  color: #8B5A2B;
  font-size: 1.25rem;
}

/* 面包屑导航样式调整 */
.bg-white.border-b {
  margin-bottom: 2rem;
}

/* 支付成功弹窗样式 */
.bg-black.bg-opacity-50 {
  backdrop-filter: blur(2px);
}
.text-green-500 {
  color: #10b981;
}

/* 弹窗动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

